package com.jigoucai.util;

import com.jigoucai.bean.dict.Dict;
import com.jigoucai.service.JedisService;
import eu.bitwalker.useragentutils.UserAgent;
import org.nutz.dao.pager.Pager;
import org.nutz.lang.Encoding;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.weixin.bean.mp.req.TokenReq;
import org.nutz.weixin.bean.mp.resp.TokenResp;
import org.nutz.weixin.util.mp.MpUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by Jianghao on 2017/2/27.
 */
public class Util {

    private static final Log log = Logs.get();

    /**
     * 校验时间戳超时
     *
     * @param time
     * @param s
     * @return
     */
    public static Boolean checkTimeout(Date time, int s) {
        if (Lang.isEmpty(time)) {
            return true;
        } else {
            if (Times.between(time, Times.now(), Times.T_1S) > (Lang.isEmpty(s) ? Dict.DOCKING_TIME : s)) {
                return true;
            } else {
                return false;
            }
        }
    }

    public static Integer o2i(Object obj) {
        if (Strings.isNumber(obj.toString())) {
            return Integer.parseInt(obj.toString());
        } else {
            return null;
        }
    }

    public static Long s2l(String str) {
        if (Strings.isNumber(str)) {
            return Long.parseLong(str);
        } else {
            return null;
        }
    }

    public static String o2s(Object obj) {
        if (!Lang.isEmpty(obj)) {
            return obj.toString();
        } else {
            return null;
        }
    }

    public static Double o2d(Object obj) {
        if (Strings.isNumber(obj.toString())) {
            return Double.parseDouble(obj.toString());
        } else {
            return null;
        }
    }

    public static Map<String, Object> sorting(Map<String, Object> params, String order) {
        if (Lang.isEmpty(params)) {
            return null;
        } else {
            Map<String, Object> map = new LinkedHashMap<>();
            if (Strings.equalsIgnoreCase(order, "desc")) {
                params.entrySet()
                        .stream()
                        .sorted(Map.Entry.<String, Object>comparingByKey().reversed())
                        .forEachOrdered(x -> map.put(x.getKey(), x.getValue()));
            } else {
                params.entrySet()
                        .stream()
                        .sorted(Map.Entry.comparingByKey())
                        .forEachOrdered(x -> map.put(x.getKey(), x.getValue()));
            }
            return map;
        }
    }

    public static Integer s2i(String s) {
        if (Strings.isNumber(s)) {
            return Integer.parseInt(s);
        } else {
            return null;
        }
    }

    public static Integer getReq(HttpServletRequest req, String para, Integer def) {
        if (Lang.isEmpty(req.getParameter(para))) {
            return def;
        } else {
            return s2i(req.getParameter(para));
        }
    }

    public static String getReq(HttpServletRequest req, String para, String def) {
        if (Strings.isEmpty(req.getParameter(para))) {
            return def;
        } else {
            return req.getParameter(para);
        }
    }

    public static Pager defaultPager(Pager pager) {
        if (pager.getPageSize() < 1) {
            pager.setPageSize(30);
        }
        if (pager.getPageNumber() < 1) {
            pager.setPageNumber(1);
        }
        return pager;
    }

    public static Pager defaultPager(int pageNumber, int pageSize) {
        return new Pager(pageNumber < 1 ? 1 : pageNumber, pageSize < 1 ? 20 : pageSize);
    }

    public static String getAgent(HttpServletRequest request) {
        if (!Lang.isEmpty(request)) {
            UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
            return "操作系统版本（" + userAgent.getOperatingSystem() + "）；浏览器版本（" + userAgent.getBrowser() + "-" + userAgent.getBrowserVersion() + "）";
        } else {
            return "";
        }
    }

    /**
     * URL转解码
     */
    public static class Url {
        /**
         * 加密
         *
         * @param s
         * @return
         */
        public static String encode(String s) {
            if (Strings.isBlank(s)) {
                log.error("s加密对象为空");
                return "";
            } else {
                try {
                    return URLEncoder.encode(s, Encoding.UTF8);
                } catch (UnsupportedEncodingException e) {
                    log.error(e.getMessage());
                    return "";
                }
            }
        }

        /**
         * 解密
         *
         * @param s
         * @return
         */
        public static String decode(String s) {
            if (Strings.isBlank(s)) {
                log.error("s解密对象为空");
                return "";
            } else {
                try {
                    return URLDecoder.decode(s, Encoding.UTF8);
                } catch (UnsupportedEncodingException e) {
                    log.error(e.getMessage());
                    return "";
                }
            }
        }
    }

    /**
     * BASE64加解密
     */
    public static class Base64 {

        /**
         * 加密
         *
         * @param s
         * @return
         */
        public static String encode(String s) {
            if (Strings.isBlank(s)) {
                log.error("s加密对象为空");
                return "";
            } else {
                return org.nutz.repo.Base64.encodeToString(s.getBytes(Encoding.CHARSET_UTF8), true);
            }
        }

        /**
         * 解密
         *
         * @param s
         * @return
         */
        public static String decode(String s) {
            if (Strings.isBlank(s)) {
                log.error("s解密对象为空");
                return "";
            } else {
                return new String(org.nutz.repo.Base64.decode(s));
            }
        }
    }

    public static double df(double d) {
        if (Lang.isEmpty(d)) {
            return 0.000;
        } else {
            BigDecimal bg = new BigDecimal(d);
            return bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
    }

    /**
     * 判断是否${prefix}开头
     *
     * @param i
     * @param prefix
     * @return
     */
    public static boolean startWith(Integer i, String prefix) {
        if (i.toString().startsWith(prefix)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断是否${prefix}开头
     *
     * @param s
     * @param prefix
     * @return
     */
    public static boolean startWith(String s, String prefix) {
        if (s.startsWith(prefix)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 构建前后
     *
     * @param url
     * @param maxPageNumber
     * @param nowPageNumber
     * @param path
     * @return
     */
    public static String bulidPageLink(String url, int maxPageNumber, int nowPageNumber, String path) {
        if (maxPageNumber <= 1) {
            return url.replaceAll("@PAGENUMBER", "1");
        }
        if (Strings.equalsIgnoreCase(path, "Next")) {
            if (nowPageNumber >= maxPageNumber) {
                return url.replaceAll("@PAGENUMBER", String.valueOf(maxPageNumber));
            } else {
                return url.replaceAll("@PAGENUMBER", String.valueOf(nowPageNumber + 1));
            }
        } else {
            if (nowPageNumber <= 1) {
                return url.replaceAll("@PAGENUMBER", "1");
            } else {
                return url.replaceAll("@PAGENUMBER", String.valueOf(nowPageNumber - 1));
            }
        }
    }

    public static String checkCodeAction(String action) {
        switch (action) {
            case "REG":
                return "";
            case "RESET_PWD":
                return "";
            case "BIND":
                return "";
            case "UNBIND":
                return "";
            case "LOGIN":
                return "";
            case "WITHDRAW":
                return "";
            case "MODIFY_PAY_PWD":
                return "";
            default:
                return "不支持的方式";
        }
    }

    public static Pattern P_REALNAME = Pattern.compile("^([a-zA-Z0-9\\u4e00-\\u9fa5\\·]{1,10})$");

    /**
     * 判断字符串是否为中文姓名<br>
     * 如：张三、噶及·洛克业
     *
     * @param s 字符串内容
     * @return 判断结果
     */
    public static boolean isRealname(String s) {
        if (Strings.isBlank(s))
            return false;
        return Strings.isMactchRegex(P_REALNAME, s);
    }

    public static String getToken(String appid, String appsecret){
        String token = JedisService.get("sys:global:token");
        if(Strings.isBlank(token)){
            TokenResp resp = MpUtil.token(new TokenReq(appid, appsecret));
            if (Lang.isEmpty(resp)){
                return null;
            }
            JedisService.set("sys:global:token", resp.getAccess_token(), Util.o2i(resp.getExpires_in()));
            return resp.getAccess_token();
        }
        return token;
    }
}
